let globalData = getApp().globalData;
import tui from '../../../common/httpRequest';
const util = require('../../../utils/util.js');
const form = require('../../../components/common/tui-validation/tui-validation.js');

Page({
  data: {
    disabled: false,
    btnText: '获取验证码',
    mobile: '',
    type: 'primary',
    code: ''
  },
  getRandom: function (u) {
    let rnd = '';
    u = u || 6;
    for (var i = 0; i < u; i++) {
      rnd += Math.floor(Math.random() * 10);
    }
    return rnd;
  },
  input: function (e) {
    this.setData({
      mobile: e.detail.value
    });
  },
  doLoop: function (seconds) {
    let code = this.getRandom(6);
    tui.toast('您本次的验证码是：' + code, 5000);
    seconds = seconds ? seconds : 60;
    this.setData({
      btnText: seconds + 's后获取',
      code: code
    })
    let countdown = setInterval(() => {
      if (seconds > 0) {
        this.setData({
            btnText: seconds + 's后获取'
          })
          --seconds;
      } else {
        this.setData({
          btnText: '获取验证码',
          disabled: false,
          type: 'primary'
        })
        clearInterval(countdown);
      }
    }, 1000);
  },
  btnSend: function () {
    let rules = [{
      name: 'mobile',
      rule: ['required', 'isMobile'],
      msg: ['请输入手机号码', '请输入正确的手机号码']
    }];
    //进行表单检查
    let formData = {
      mobile: this.data.mobile
    };
    let checkRes = form.validation(formData, rules);
    if (!checkRes) {
      this.setData({
        disabled: true,
        btnText: "请稍候...",
        type: "gray"
      })
      setTimeout(() => {
        this.doLoop(60);
      }, 500);
    } else {
      tui.toast(checkRes);
    }
  },
  formLogin: function (e) {
    let loginCode = e.detail.value.smsCode;
    let mobile = e.detail.value.mobile;
    let rules = [{
        name: 'mobile',
        rule: ['required', 'isMobile'],
        msg: ['请输入手机号码', '请输入正确的手机号码']
      },
      {
        name: 'loginCode',
        rule: ['required', 'isSame:code'],
        msg: ['请输入验证码', '验证码不正确']
      }
    ];
    //进行表单检查
    let formData = {
      mobile: mobile,
      loginCode: loginCode,
      code: this.data.code
    };
    let checkRes = form.validation(formData, rules);
    if (checkRes) {
      tui.toast(checkRes);
      return;
    }
    let format = util.formatNumber(mobile);
    tui.setUserInfo(format)
    globalData.isLogin = true;
    globalData.mobile = format;
    tui.toast('登录成功', 2000, true);
    setTimeout(() => {
      wx.reLaunch({
        url: '/pages/tabbar/my/my'
      });
    }, 200);
  },
  protocol: function () {
    tui.href("/pages/doc/protocol/protocol")
  }
})